package file

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path"
)

func init() {

}

func Write(filePath string, content interface{}) error {
	json, err := json.Marshal(content)
	if err != nil {
		return err
	}

	if json != nil {
		dirPath := path.Dir(filePath)
		err := os.MkdirAll(dirPath, os.ModePerm)
		if err != nil {
			// fmt.Fatal(mkErr)
			return err
		}

		err = ioutil.WriteFile(filePath, json, os.ModePerm)
		if err != nil {
			// fmt.Fatal(writeErr)
			return err
		}
	}

	return nil
}

func Read(filePath string, content interface{}) error {
	_, err := os.Stat(filePath)
	if os.IsNotExist(err) {
		return err
	}

	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		//Log load config failure
		return err
	}

	err = json.Unmarshal(data, &content)
	if err != nil {
		return err
	}
	return nil
}
